package training;

/**
 * @Author liangzai
 * @Description:
 */
public class J25_5_17_Training {
    //颜色分类
    public void sortColors(int[] nums) {
        int[] map = new int[3];
        for (int i = 0; i < nums.length; i++) {
            map[nums[i]]++;
        }
        for (int i = 0, j = 0; i < map.length; i++) {
            int n = map[i];
            for (int k = 0; k < n; k++) {
                nums[j++] = i;
            }
        }
    }


    //排序列表
    public ListNode sortList(ListNode head) {
        return mergeSort(head);
    }

    private ListNode mergeSort(ListNode head) {
        if (head == null || head.next == null)
            return head;

        ListNode slow = head, fast = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode l2Head = slow.next;
        slow.next = null;
        ListNode l = mergeSort(head);
        ListNode r = mergeSort(l2Head);
        return merge(l, r);
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);
        ListNode hair = pre;
        while (l1 != null && l2 != null) {
            if (l1.val > l2.val) {
                pre.next = l2;
                l2 = l2.next;
            } else {
                pre.next = l1;
                l1 = l1.next;
            }
            pre = pre.next;
        }
        pre.next = l1 == null ? l2 : l1;
        return hair.next;
    }
}
